package com.zdltech.lightappupdatelib.net;

import android.support.annotation.NonNull;

import com.zdltech.lightappupdatelib.utils.HttpURLConnectUtils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Http工具管理
 * 由于是轻量的故没有使用到第三方的网络请求框架
 * 使用Android原生的 Http连接
 *
 * @ Des
 * @ Author jason
 */

public class HttpCoreManager implements HttpManager {
    private boolean isRuning;//是否正在运行 get和POST只能同时运行一个
    private boolean isDownLoadRuning;//下载是否正在运行 同一时刻只有一个下载

    private static HttpCoreManager manager;

    public static HttpCoreManager getInstance() {
        return Lazy.INSTNCE;
    }

    private static class Lazy {
        private static HttpCoreManager INSTNCE = new HttpCoreManager();
    }

    /**
     * Get请求
     *
     * @param url      get请求地址
     * @param params   get参数
     * @param callBack 回调
     */
    public void asyncGet(@NonNull final String url, @NonNull final Map<String, String> params, @NonNull final Callback callBack) {
        if (!isRuning) {
            isRuning = true;
            Thread thread = new Thread() {
                @Override
                public void run() {
                    HttpURLConnectUtils.get(url, params, callBack);
                    isRuning = false;
                }
            };
            thread.start();
        }

    }

    /**
     * POST请求
     *
     * @param url      post请求地址
     * @param params   post请求参数
     * @param callBack 回调
     */
    public void asyncPost(@NonNull final String url, final @NonNull Map<String, String> params, final @NonNull Callback callBack) {
        if (!isRuning) {
            isRuning = true;
            Thread thread = new Thread() {
                @Override
                public void run() {
                    HttpURLConnectUtils.post(url, params, callBack);
                    isRuning = false;
                }
            };
            thread.start();
        }
    }


    /**
     * 下载
     *
     * @param url      下载地址
     * @param path     文件保存路径
     * @param fileName 文件名称
     * @param callback 回调
     */
    public void download(@NonNull final String url, @NonNull final String path, @NonNull final String fileName, @NonNull final FileCallback callback) {
        if (!isDownLoadRuning) {
            isDownLoadRuning = true;
            Thread thread = new Thread() {
                @Override
                public void run() {
                    HttpURLConnectUtils.downloadFile(url,path,fileName,callback);
                    isDownLoadRuning = false;
                }
            };
            thread.start();
        }
    }

}
